<template>
  <div :id="uuid"></div>
</template>
<script>
// vue中使用vue组件在同一页面复用echarts，会只显示后面的图表，前面的图表会被覆盖的问题，这是因为echarts的id在写的时候写成固定值，所以后面的id会覆盖前面的id，进而后面的图表也会覆盖前面的图表，只显示一个图表的问题，可以使用uuid数据使之id为动态的数据
import * as echarts from "echarts/core";
import {
  TitleComponent,
  GridComponent,
  DataZoomComponent,
} from "echarts/components";
import { BarChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";
import { TooltipComponent } from "echarts/components";
import { PieChart } from "echarts/charts";
echarts.use([PieChart]);
echarts.use([TooltipComponent]);
echarts.use([
  TitleComponent,
  GridComponent,
  DataZoomComponent,
  BarChart,
  CanvasRenderer,
]);
let idGen=()=>{
      return window.performance.now();
    }
export default {
  name: "pic",
  data() {
    return {
      uuid: null,
      list: [],
      categoryList: [
        "工资收入",
        "利息收入",
        "投资收入",
        "中奖收入",
        "废旧物品",
        "微信红包",
        "其他收入",
      ],
      cate1: [
        "工资收入",
        "利息收入",
        "投资收入",
        "中奖收入",
        "废旧物品",
        "微信红包",
        "其他收入",
      ],
      cate2: [
        "衣服饰品",
        "食品酒水",
        "居家物业",
        "行车交通",
        "交流通讯",
        "休闲娱乐",
        "学习进修",
        "人情往来",
        "医疗保健",
        "金融保险",
        "其他杂项",
      ],
    };
  },
  props: ["cate"],
  created() {
    this.uuid = idGen();
  },
  mounted() {
    this.draw();
  },
  methods: {
    
    draw() {
      //遍历类别发送请求 响应式的数组无法使用常用方法
      let i = 0;
      let data = [];
      if (this.cate == "收入") {
        this.categoryList = this.cate1;
      } else this.categoryList = this.cate2;
      let cName = this.categoryList;
      this.categoryList.map(async (item) => {
        // 因为是模糊查询所以也可以用来分类
        let re = null;
        if (this.cate == "收入") {
          re = await this.$API.income.returnMonthIncome(item);
        } else {
          re = await this.$API.table.returnMonthSpending(item);
          // console.log(re)
        }
        let sum = 0;
        if (re.data.length) {
          re.data.map((item) => {
            sum += parseInt(item.price);
          });
        }
        this.list[i] = sum;
        if (i == this.categoryList.length - 1) {
          // console.log(this.list)
          data = JSON.parse(JSON.stringify(this.list));
        }
        i++;
      });
      // 需要一段时间让data的值出来
      setTimeout(() => {
        var chartDom = document.getElementById(this.uuid);
        chartDom.style.width='500px'
        chartDom.style.height='270px'
        var myChart = echarts.init(chartDom);
        var option;
        // prettier-ignore
        let dataAxis = this.categoryList
        let yMax = 500;
        let dataShadow = [];
        // console.log(data);
        let title=`不同类别${this.cate}情况`
        data.map((item) => {
          if (item == 0) {
            var index = data.indexOf(item);
            if (index > -1) {
              this.categoryList.splice(index, 1);
              data.splice(index, 1);
              // console.log(data);
            }
          }
          // console.log(data)
        });
        // console.log(data)
        for (let i = 0; i < data.length; i++) {
          dataShadow.push(yMax);
        }
        option = {
          backgroundColor: "#F3F6FA",
          title: {
            text:title,
            left: "center",
            // top:'middle',
            textStyle: {
              color: "black",
              fontWeight: "normal",
              fontSize: 18,
            },
          },
          tooltip: {},
          xAxis: {
            data: dataAxis,
            axisLabel: {
              inside: true,
              color: "black",
            //   formatter: function (value) {
            //   const str = value.split('');
            //   return str.join('\n');
            // }

            },
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            z: 10,
          },
          yAxis: {
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              color: "#999",
            },
          },
          grid: {
            top: 20,
            left: 40,
            bottom: 10,
          },
          dataZoom: [
            {
              type: "inside",
            },
          ],
          series: [
            {
              type: "bar",
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: "#83bff6" },
                  { offset: 0.5, color: "#188df0" },
                  { offset: 1, color: "#188df0" },
                ]),
              },
              emphasis: {
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: "#2378f7" },
                    { offset: 0.7, color: "#2378f7" },
                    { offset: 1, color: "#83bff6" },
                  ]),
                },
              },
              data: data,
            },
            {
              type: "pie",
              data: (function () {
                var res = [];
                var len = data.length;
                while (len--) {
                  res.push({
                    name: cName[len],
                    value: data[len],
                  });
                }
                return res;
              })(),
              width: 150,
              height: 150,
              left: "right",
              label: {
                show: false,
              },
            },
          ],
        };
        // Enable data zoom when user click bar.
        const zoomSize = 6;
        myChart.on("click", function (params) {
          // console.log(dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)]);
          myChart.dispatchAction({
            type: "dataZoom",
            startValue: dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)],
            endValue:
              dataAxis[
                Math.min(params.dataIndex + zoomSize / 2, data.length - 1)
              ],
          });
        });
        option && myChart.setOption(option);
      }, 1000);
      // 去除数据检控添加的属性拿到数组本身，否则数组很多方法都不能使用
      // this.list=JSON.stringify(this.list)
      // console.log(this.list)
    },
  },
};
</script>

<style scoped>
</style>